/*
// 用户行为监控服务 - 已注释
// 如需重新启用，请取消注释

using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Repositories;
using System.Text.Json;

namespace Lzfy_Refund_Service.Services
{
    public interface IUserBehaviorService
    {
        Task<bool> TrackUserActionAsync(BehaviorTrackingRequest request, string userId, string? userAgent = null, string? ipAddress = null);
        Task<BehaviorAnalysisResult> AnalyzeSessionAsync(string sessionId);
        Task<UserOperationSession?> StartOperationSessionAsync(string sessionId, string userId, long taskDetailId, string patientId, string? patientName = null, string? phoneNumber = null);
        Task<bool> UpdateOperationSessionAsync(string sessionId, string actionType, object? actionData = null);
        Task<bool> CompleteOperationSessionAsync(string sessionId, string contactResult, string? userNotes = null);
        Task<IEnumerable<UserOperationSession>> GetSuspiciousOperationsAsync(decimal minRiskScore = 5.0m);
        Task<UserBehaviorStatistics> GetUserDailyStatisticsAsync(string userId, DateTime date);
        Task<bool> UpdateDailyStatisticsAsync(string userId, DateTime date);
    }

    public class UserBehaviorService : IUserBehaviorService
    {
        private readonly IUserBehaviorRepository _behaviorRepository;
        private readonly ILogger<UserBehaviorService> _logger;

        public UserBehaviorService(IUserBehaviorRepository behaviorRepository, ILogger<UserBehaviorService> logger)
        {
            _behaviorRepository = behaviorRepository;
            _logger = logger;
        }

        public async Task<bool> TrackUserActionAsync(BehaviorTrackingRequest request, string userId, string? userAgent = null, string? ipAddress = null)
        {
            try
            {
                var log = new UserBehaviorLog
                {
                    UserId = userId,
                    SessionId = request.SessionId,
                    TaskDetailId = request.TaskDetailId,
                    PatientId = request.PatientId,
                    ActionType = request.ActionType,
                    ActionData = request.ActionData != null ? JsonSerializer.Serialize(request.ActionData) : null,
                    Timestamp = DateTime.Now,
                    PageUrl = request.PageUrl,
                    UserAgent = userAgent,
                    IpAddress = ipAddress
                };

                await _behaviorRepository.CreateBehaviorLogAsync(log);

                // 如果是关键操作，更新操作会话
                if (IsKeyAction(request.ActionType))
                {
                    await UpdateOperationSessionAsync(request.SessionId, request.ActionType, request.ActionData);
                }

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "跟踪用户行为失败: {UserId}, {ActionType}", userId, request.ActionType);
                return false;
            }
        }

        public async Task<UserOperationSession?> StartOperationSessionAsync(string sessionId, string userId, long taskDetailId, string patientId, string? patientName = null, string? phoneNumber = null)
        {
            try
            {
                var session = new UserOperationSession
                {
                    SessionId = sessionId,
                    UserId = userId,
                    TaskDetailId = taskDetailId,
                    PatientId = patientId,
                    PatientName = patientName,
                    PhoneNumber = phoneNumber,
                    StartTime = DateTime.Now,
                    IsCompleted = false
                };

                await _behaviorRepository.CreateOperationSessionAsync(session);
                return session;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始操作会话失败: {SessionId}, {UserId}", sessionId, userId);
                return null;
            }
        }

        public async Task<bool> UpdateOperationSessionAsync(string sessionId, string actionType, object? actionData = null)
        {
            try
            {
                _logger.LogInformation("开始更新操作会话: SessionId={SessionId}, ActionType={ActionType}", sessionId, actionType);
                
                // 添加重试机制，因为会话可能刚刚创建还未完全建立
                UserOperationSession? session = null;
                int retryCount = 0;
                const int maxRetries = 3;
                const int retryDelayMs = 200;

                while (session == null && retryCount < maxRetries)
                {
                    session = await _behaviorRepository.GetOperationSessionAsync(sessionId);
                    if (session == null)
                    {
                        retryCount++;
                        if (retryCount < maxRetries)
                        {
                            _logger.LogWarning("会话 {SessionId} 暂未找到，第 {RetryCount} 次重试", sessionId, retryCount);
                            await Task.Delay(retryDelayMs);
                        }
                    }
                }

                if (session == null)
                {
                    _logger.LogWarning("会话 {SessionId} 不存在，无法更新操作: {ActionType}", sessionId, actionType);
                    return false;
                }

                _logger.LogInformation("找到会话: SessionId={SessionId}, 当前状态: PhoneViewTime={PhoneViewTime}, FirstInputTime={FirstInputTime}, SaveTime={SaveTime}", 
                    sessionId, session.PhoneViewTime, session.FirstInputTime, session.SaveTime);

                var now = DateTime.Now;

                switch (actionType)
                {
                    case ActionTypes.VIEW_PHONE:
                        _logger.LogInformation("更新PhoneViewTime: SessionId={SessionId}, Time={Time}", sessionId, now);
                        session.PhoneViewTime = now;
                        break;

                    case ActionTypes.INPUT_NOTES:
                        _logger.LogInformation("更新InputNotes时间: SessionId={SessionId}, FirstInputTime={FirstInputTime}, Time={Time}", 
                            sessionId, session.FirstInputTime, now);
                        if (session.FirstInputTime == null)
                            session.FirstInputTime = now;
                        session.LastInputTime = now;
                        
                        // 计算输入字符数
                        if (actionData != null)
                        {
                            var inputData = JsonSerializer.Deserialize<Dictionary<string, object>>(JsonSerializer.Serialize(actionData));
                            if (inputData?.ContainsKey("text") == true)
                            {
                                var text = inputData["text"]?.ToString() ?? "";
                                session.InputCharCount = text.Length;
                                _logger.LogInformation("更新InputCharCount: SessionId={SessionId}, CharCount={CharCount}", sessionId, text.Length);
                            }
                        }
                        break;

                    case ActionTypes.SELECT_RESULT:
                        _logger.LogInformation("更新SelectResult: SessionId={SessionId}", sessionId);
                        if (actionData != null)
                        {
                            var resultData = JsonSerializer.Deserialize<Dictionary<string, object>>(JsonSerializer.Serialize(actionData));
                            if (resultData?.ContainsKey("result") == true)
                            {
                                session.ContactResult = resultData["result"]?.ToString();
                                _logger.LogInformation("更新ContactResult: SessionId={SessionId}, Result={Result}", sessionId, session.ContactResult);
                            }
                        }
                        break;

                    case ActionTypes.SAVE_CONTACT:
                        _logger.LogInformation("更新SaveContact: SessionId={SessionId}, Time={Time}", sessionId, now);
                        session.SaveTime = now;
                        session.IsCompleted = true;
                        
                        // 处理保存的数据
                        if (actionData != null)
                        {
                            var saveData = JsonSerializer.Deserialize<Dictionary<string, object>>(JsonSerializer.Serialize(actionData));
                            if (saveData?.ContainsKey("userNotes") == true)
                            {
                                session.UserNotes = saveData["userNotes"]?.ToString();
                            }
                            if (saveData?.ContainsKey("contactResult") == true)
                            {
                                session.ContactResult = saveData["contactResult"]?.ToString();
                            }
                        }
                        
                        // 计算各种时长
                        CalculateSessionDurations(session);
                        
                        // 分析风险
                        var analysisResult = await AnalyzeSessionRiskAsync(session);
                        session.RiskScore = analysisResult.RiskScore;
                        session.RiskFactors = JsonSerializer.Serialize(analysisResult.RiskFactors);
                        break;
                }

                _logger.LogInformation("准备更新数据库: SessionId={SessionId}, PhoneViewTime={PhoneViewTime}, FirstInputTime={FirstInputTime}, SaveTime={SaveTime}", 
                    sessionId, session.PhoneViewTime, session.FirstInputTime, session.SaveTime);

                await _behaviorRepository.UpdateOperationSessionAsync(session);
                
                _logger.LogInformation("数据库更新完成: SessionId={SessionId}", sessionId);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新操作会话失败: {SessionId}, {ActionType}", sessionId, actionType);
                return false;
            }
        }

        public async Task<bool> CompleteOperationSessionAsync(string sessionId, string contactResult, string? userNotes = null)
        {
            try
            {
                var session = await _behaviorRepository.GetOperationSessionAsync(sessionId);
                if (session == null) return false;

                session.ContactResult = contactResult;
                session.UserNotes = userNotes;
                session.SaveTime = DateTime.Now;
                session.IsCompleted = true;

                // 计算各种时长
                CalculateSessionDurations(session);

                // 分析风险
                var analysisResult = await AnalyzeSessionRiskAsync(session);
                session.RiskScore = analysisResult.RiskScore;
                session.RiskFactors = JsonSerializer.Serialize(analysisResult.RiskFactors);

                await _behaviorRepository.UpdateOperationSessionAsync(session);

                // 更新当日统计
                await UpdateDailyStatisticsAsync(session.UserId, DateTime.Today);

                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "完成操作会话失败: {SessionId}", sessionId);
                return false;
            }
        }

        public async Task<BehaviorAnalysisResult> AnalyzeSessionAsync(string sessionId)
        {
            try
            {
                var session = await _behaviorRepository.GetOperationSessionAsync(sessionId);
                if (session == null)
                {
                    return new BehaviorAnalysisResult
                    {
                        SessionId = sessionId,
                        RiskScore = 0,
                        IsSuspicious = false,
                        Recommendation = "会话不存在"
                    };
                }

                return await AnalyzeSessionRiskAsync(session);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析会话失败: {SessionId}", sessionId);
                return new BehaviorAnalysisResult
                {
                    SessionId = sessionId,
                    RiskScore = 0,
                    IsSuspicious = false,
                    Recommendation = "分析失败"
                };
            }
        }

        public async Task<IEnumerable<UserOperationSession>> GetSuspiciousOperationsAsync(decimal minRiskScore = 5.0m)
        {
            return await _behaviorRepository.GetSuspiciousSessionsAsync(minRiskScore);
        }

        public async Task<UserBehaviorStatistics> GetUserDailyStatisticsAsync(string userId, DateTime date)
        {
            var stats = await _behaviorRepository.GetUserStatisticsAsync(userId, date);
            if (stats == null)
            {
                // 如果没有统计数据，创建一个空的
                stats = new UserBehaviorStatistics
                {
                    UserId = userId,
                    StatDate = date.Date,
                    TotalOperations = 0,
                    CompletedOperations = 0
                };
            }
            return stats;
        }

        public async Task<bool> UpdateDailyStatisticsAsync(string userId, DateTime date)
        {
            try
            {
                var startDate = date.Date;
                var endDate = startDate.AddDays(1);

                // 获取当日的操作会话
                var sessions = await _behaviorRepository.GetUserOperationSessionsAsync(userId, startDate, endDate);
                var sessionList = sessions.ToList();

                if (!sessionList.Any())
                {
                    return true; // 没有数据也算成功
                }

                var completedSessions = sessionList.Where(s => s.IsCompleted).ToList();
                var durations = completedSessions.Where(s => s.TotalDuration.HasValue).Select(s => s.TotalDuration!.Value).ToList();

                var statistics = new UserBehaviorStatistics
                {
                    UserId = userId,
                    StatDate = date.Date,
                    TotalOperations = sessionList.Count,
                    CompletedOperations = completedSessions.Count,
                    AvgDuration = durations.Any() ? (decimal)durations.Average() : null,
                    MinDuration = durations.Any() ? durations.Min() : null,
                    MaxDuration = durations.Any() ? durations.Max() : null,
                    SuspiciousOperations = sessionList.Count(s => s.RiskScore >= RiskLevels.HIGH),
                    AvgRiskScore = sessionList.Where(s => s.RiskScore.HasValue).Any() ? 
                        sessionList.Where(s => s.RiskScore.HasValue).Average(s => s.RiskScore!.Value) : null
                };

                await _behaviorRepository.CreateOrUpdateStatisticsAsync(statistics);
                return true;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新每日统计失败: {UserId}, {Date}", userId, date);
                return false;
            }
        }

        #region 私有方法

        private static bool IsKeyAction(string actionType)
        {
            return actionType switch
            {
                ActionTypes.SESSION_START => true,
                ActionTypes.SESSION_COMPLETE => true,
                ActionTypes.VIEW_DETAILS => true,
                ActionTypes.VIEW_PHONE => true,
                ActionTypes.INPUT_NOTES => true,
                ActionTypes.SELECT_RESULT => true,
                ActionTypes.SAVE_CONTACT => true,
                ActionTypes.PAGE_FOCUS => true,
                ActionTypes.PAGE_BLUR => true,
                _ => false
            };
        }

        private static void CalculateSessionDurations(UserOperationSession session)
        {
            if (session.SaveTime.HasValue)
            {
                // 总耗时
                session.TotalDuration = (int)(session.SaveTime.Value - session.StartTime).TotalSeconds;

                // 查看电话到保存的耗时
                if (session.PhoneViewTime.HasValue)
                {
                    session.PhoneToSaveDuration = (int)(session.SaveTime.Value - session.PhoneViewTime.Value).TotalSeconds;
                }

                // 输入耗时
                if (session.FirstInputTime.HasValue && session.LastInputTime.HasValue)
                {
                    session.InputDuration = (int)(session.LastInputTime.Value - session.FirstInputTime.Value).TotalSeconds;
                }
            }
        }

        private async Task<BehaviorAnalysisResult> AnalyzeSessionRiskAsync(UserOperationSession session)
        {
            var result = new BehaviorAnalysisResult
            {
                SessionId = session.SessionId,
                RiskFactors = new List<string>()
            };

            var rules = await _behaviorRepository.GetActiveRulesAsync();
            decimal totalRiskScore = 0;

            foreach (var rule in rules)
            {
                var riskScore = AnalyzeByRule(session, rule, result.RiskFactors);
                totalRiskScore += riskScore * rule.Weight;
            }

            // 获取用户历史平均操作时间进行对比
            var userAvgTime = await _behaviorRepository.CalculateUserAverageOperationTimeAsync(session.UserId);
            if (userAvgTime > 0 && session.TotalDuration.HasValue)
            {
                var deviation = Math.Abs(session.TotalDuration.Value - (int)userAvgTime) / userAvgTime;
                if (deviation > 0.5m) // 偏离超过50%
                {
                    totalRiskScore += 1.0m;
                    result.RiskFactors.Add($"操作时长偏离个人平均值{deviation:P0}");
                }
            }

            result.RiskScore = Math.Min(totalRiskScore, 10.0m); // 最高10分
            result.IsSuspicious = result.RiskScore >= RiskLevels.HIGH;
            result.Recommendation = GenerateRecommendation(result.RiskScore, result.RiskFactors);

            return result;
        }

        private static decimal AnalyzeByRule(UserOperationSession session, BehaviorAnalysisRule rule, List<string> riskFactors)
        {
            decimal riskScore = 0;

            switch (rule.RuleType)
            {
                case "DURATION":
                    if (session.TotalDuration.HasValue)
                    {
                        if (rule.MinDuration.HasValue && session.TotalDuration < rule.MinDuration)
                        {
                            riskScore = 2.0m;
                            riskFactors.Add($"操作时长过短({session.TotalDuration}秒，正常范围{rule.MinDuration}-{rule.MaxDuration}秒)");
                        }
                        else if (rule.MaxDuration.HasValue && session.TotalDuration > rule.MaxDuration)
                        {
                            riskScore = 1.0m;
                            riskFactors.Add($"操作时长过长({session.TotalDuration}秒，正常范围{rule.MinDuration}-{rule.MaxDuration}秒)");
                        }
                    }
                    break;

                case "INPUT_SPEED":
                    if (session.InputDuration.HasValue && session.InputCharCount.HasValue && session.InputDuration > 0)
                    {
                        var charsPerSecond = (decimal)session.InputCharCount.Value / session.InputDuration.Value;
                        if (rule.MaxInputSpeed.HasValue && charsPerSecond > rule.MaxInputSpeed)
                        {
                            riskScore = 2.0m;
                            riskFactors.Add($"输入速度过快({charsPerSecond:F1}字符/秒，正常上限{rule.MaxInputSpeed}字符/秒)");
                        }
                        else if (rule.MinInputSpeed.HasValue && charsPerSecond < rule.MinInputSpeed)
                        {
                            riskScore = 1.0m;
                            riskFactors.Add($"输入速度过慢({charsPerSecond:F1}字符/秒，正常下限{rule.MinInputSpeed}字符/秒)");
                        }
                    }
                    break;

                case "PATTERN":
                    // 检查操作模式
                    if (session.PhoneViewTime.HasValue && session.SaveTime.HasValue)
                    {
                        var phoneToSave = (session.SaveTime.Value - session.PhoneViewTime.Value).TotalSeconds;
                        if (phoneToSave < 5) // 查看电话后5秒内就保存，可能是虚假操作
                        {
                            riskScore = 3.0m;
                            riskFactors.Add($"查看电话后立即保存({phoneToSave:F0}秒)，疑似虚假操作");
                        }
                    }
                    break;

                case "BATCH":
                    // 批量操作检测在Repository层实现
                    break;
            }

            return riskScore;
        }

        private static string GenerateRecommendation(decimal riskScore, List<string> riskFactors)
        {
            if (riskScore >= RiskLevels.HIGH)
            {
                return "高风险操作，建议人工审核";
            }
            else if (riskScore >= RiskLevels.MEDIUM)
            {
                return "中等风险操作，建议关注";
            }
            else if (riskScore >= RiskLevels.LOW)
            {
                return "低风险操作，正常范围";
            }
            else
            {
                return "正常操作";
            }
        }

        #endregion
    }
}
*/